<template>
  <div class="content">
    <table v-if="cartList.length > 0" class="shopping">
      <tr>
        <td colspan="4">
          <el-button type="primary" size="small" 
          @click="router.push('/address')"
          > 添加地址 </el-button>
        </td>
      </tr>
      <tr v-for="item in adrList" :key="item.addressid">
        <td colspan="4">
          <el-radio
            size="small"
            :value="item.addressid"
            v-model="formData.addressid"
            >{{
              `${item.receiver},${item.phoneno},,${item.province},${item.city},${item.county},${item.details}`
            }}</el-radio
          >
        </td>
      </tr>
      <tr>
        <th>商品名称</th>
        <th>商品价格</th>
        <th>购买数量</th>
        <th>操作</th>
      </tr>
      <tr class="product" v-for="item in cartList" :key="item.cartid">
        <td>
          <span class="click" @click="showGoods(item.goodsid)">
            {{ item.goodsname }}
          </span>
        </td>
        <td class="price">￥{{ item.goodsprice }}</td>
        <td>
          <el-input-number
            size="small"
            v-model="item.num"
            @change="changeNum(item)"
          />
        </td>
        <td>
          <el-button type="danger" size="small" @click="handleDel(item)">
            删除
          </el-button>
        </td>
      </tr>
    </table>
    <div class="balance" v-if="cartList.length > 0">
      <div class="btn" @click="balance"></div>
    </div>
    <el-card v-else class="msg" style="max-width: 480px">
      购物车空空如也!!!!
    </el-card>

    <el-dialog
      append-to-body
      v-model="showGoodsVisible"
      title="查看商品"
      width="700"
      center
    >
      <div class="product">
        <h1>{{ showGoodsData.goodsname }}</h1>
      </div>
      <div class="infos">
        <div class="thumb">
          <el-image
            style="width: 300px; height: 300px"
            :src="showGoodsData.goodsimg"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="srcList"
            :initial-index="4"
            fit="cover"
          />
        </div>
        <div class="buy">
          <p>
            价格:<span class="price">￥{{ showGoodsData.goodsprice }}</span>
          </p>
          <p>
            库存:<span>{{ showGoodsData.goodsstock }}</span>
          </p>
          <p>
            状态:<span>{{
              showGoodsData.goodsstatus == 1 ? "上架" : "下架"
            }}</span>
          </p>
          <p>
            详情:<span> {{ showGoodsData.goodsdetails }}</span>
          </p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, onMounted } from "vue";
import { useStore } from "vuex";
import { getAddressList } from "@/api/address";
import { getCartBy, delCart, updCart, account } from "@/api/cart";
import { getById } from "@/api/goods";
import { CODE } from "@/utils/StatusCode";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter, useRoute } from "vue-router";

const router = useRouter();
const store = useStore();

const userInfo = computed(() => {
  return store.getters.getUserInfo;
});
onMounted(() => {
  getAdrList();
  getCartList();
});

const formData = reactive({
  userid: userInfo.value.userid,
  addressid: null,
});
// 获取地址数据
interface address {
  addressid: number;
  userid: number;
  receiver: string;
  phoneno: string;
  province: string;
  city: string;
  county: string;
  details: string;
  isdefault: number;
}
const adrList = ref<address[]>([]);
async function getAdrList() {
  const res = await getAddressList({ userid: userInfo.value.userid });
  if (res.code == CODE.OK) {
    adrList.value = res.data;
  }
}
// 获取购物车列表
interface cart {
  cartid: number;
  userid: number;
  goodsid: number;
  num: number;
  goodsname: string;
  goodsprice: number;
}
const cartList = ref<cart[]>([]);
async function getCartList() {
  const res = await getCartBy({ userid: userInfo.value.userid });
  if (res.code == CODE.OK) {
    cartList.value = res.data;
  }
}
// 删除商品
function handleDel(row: any) {
  if (!row.cartid) return;
  ElMessageBox.confirm("是否删除此商品", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await delCart({
        cartid: row.cartid,
      });
      if (res.code == CODE.OK) {
        getCartList();
      }
      prompt(res);
    })
    .catch(() => {});
}
function prompt(res: any) {
  if (res.code == CODE.OK) {
    ElMessage({
      message: res.message,
      type: "success",
    });
  } else {
    ElMessage({
      message: res.message,
      type: "error",
    });
  }
}
//查看商品
interface goods {
  goodsid: number;
  categoryid: number;
  goodsname: string;
  goodsimg: string;
  goodsprice: number;
  promotiontype: number;
  goodsstatus: number;
  goodsstock: number;
  goodsdetails: string;
}
const showGoodsVisible = ref(false);
let srcList: string[] = [""];
const showGoodsData = reactive<goods>({
  goodsid: 0,
  categoryid: 0,
  goodsname: "",
  goodsimg: "",
  goodsprice: 0,
  promotiontype: 0,
  goodsstock: 0,
  goodsstatus: 0,
  goodsdetails: "",
});
function showGoods(goodsid: number) {
  if (!goodsid) return;
  getGoodsById(goodsid);
  showGoodsVisible.value = true;
}
async function getGoodsById(goodsid: number) {
  const res = await getById({
    goodsid: goodsid,
  });
  if (res.code == CODE.OK) {
    Object.keys(showGoodsData).forEach((fieId) => {
      showGoodsData[fieId] = res.data[fieId];
    });
    srcList[0] = showGoodsData.goodsimg;
  }
}
// 修改数量
function changeNum(cart: cart) {
  if (!cart.cartid) return;
  updCart({
    cartid: cart.cartid,
    num: cart.num,
  });
}
// 结算
function balance() {
  if (!formData.addressid) {
    ElMessage({
      message: "请选择收货地址",
      type: "warning",
    });
    return;
  }
  ElMessageBox.confirm("是否进行结算", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await account(formData);
      if (res.code == CODE.OK) {
        setTimeout(() => {
          router.push("/foreground");
        }, 2000);
      }
      prompt(res);
    })
    .catch(() => {});
}
</script>

<style lang="less" scoped>
.content {
  padding: 20px;
}
.msg {
  text-align: center;
}
.shopping {
  width: 100%;
  border-top: 2px solid #dfc9b2;
  border-bottom: 2px solid #dfc9b2;
  tr {
    height: 24px;
    line-height: 24px;

    th {
      background: #f7f4eb;
      color: #8a7152;
    }
    td {
      padding: 10px 0;
      border-top: 1px solid #dfc9b2;
    }
  }
  .product {
    text-align: center;
    > td:nth-child(1) {
      width: 350px;
    }
    > td:last-child {
      border-right: 1px solid #e1e1e1;
    }
    td {
      border-left: 1px solid #e1e1e1;
    }
  }
}
.price {
  color: #cc3300;
  font-weight: bold;
}
.click {
  cursor: pointer;
  color: #3a52a8;
  &:hover {
    color: #4091ff;
  }
}
.product {
  border-bottom: 1px dashed #cfcfcf;
}
.infos {
  margin-top: 10px;
  display: flex;
  .thumb {
    width: 300px;
  }
  .buy {
    width: 440px;
    line-height: 40px;
    padding-left: 10px;
    span {
      padding-left: 4px;
    }
    .price {
      color: #c00;
      font-weight: bold;
      font-size: 24px;
    }
  }
}
.balance {
  margin-top: 6px;
  float: right;
  .btn {
    background: url(../../assets/img/bg.png) left -213px;
    width: 144px;
    height: 35px;
    cursor: pointer;
  }
}
</style>
